<?php
class Order
{
	public function __construct()
	{
		if(!isset($_SESSION['cartid']))
		{
			srand();
			$_SESSION['cartid']=rand();
			$cartid=$_SESSION['cartid'];
		} else {
			$cartid=$_SESSION['cartid'];
		}
		
		$this->cartid=$cartid;
	}
	
	public function index()
	{		
		CommonFunc::loadFile("controller/LoginController.php");
		CommonFunc::loadFile(ADAPTOR . "Mail.php");
		CommonFunc::loadFile("model/Cart.php");
		CommonFunc::loadFile("model/User.php");
		CommonFunc::loadFile("model/Order.php");
		//CommonFunc::loadFile(ADAPTOR . "Savecart.php");	
                $request = CommonFunc::getRequest();
		//CommonFunc::loadFile(CPANELURL."model/Creditor.php");
               // $modcredit=new ModelCreditor();
		$clsLogin = new Login();
		$modCart = new FrontCart();
		$modUser = new FrontUser();
		$modOrder = new FrontOrder();
                $creditbalance=$modOrder->creditbalance($_SESSION["user_id"]);
                $iscredituser=$modOrder->iscredituser($_SESSION["user_id"]);
                $ordsucmes="";
		$modSaveCart = new SaveCartHelper();
		$request = CommonFunc::getRequest();
		$savecartid = $request['savecartid'];
		$userid = CommonFunc::currentUserId();
		//$savecart_arr = $modCart->getSaveCartDetailsByUserId($userid);
		
		
		if(!isset($_SESSION['user_id']))
		{
			$arg = 'checkout';
			include SITETPL . "user/login.phtml";			
		} else {
			if($savecartid == "")
			{
				$cart_arr = $modCart->getCart();
				$cart_id = $this->cartid;
			} else {
				$cart_arr = $modCart->getSaveCartDetailsByCartId($savecartid);
				$cart_id = $savecartid;
			}
			
			
			
			$user_arr = $modUser->getUserInfoById();
			
			if(isset($request['btnOrderConfirm']))
			{
				$sender_email = $request['txtEmail'];
				$modOrder->addOrderProcess();
				
				$last_order_id_arr = $modOrder->lastInsertedOrderId();
				$last_order_id = $last_order_id_arr['order_id'];
				$order_date = $last_order_id_arr['order_date'];
				
				$message = "
		        <p>Hi {$user_arr['user_firstname']}&nbsp;{$user_arr['user_lastname']},</p>		        
		       	<p>Thank you for your order on {$order_date}. One of our member will contact you soon.</p>
		       	<p>...................................................................................................</p>
		       	<p><b>Order Summary</b></p>";
		       	$message .= "<table border=\"\" cellpadding=\"2\" cellspacing=\"1\" width=\"98%\" style=\"line-height: 32px;\">";
				$message .= "<tr>";
				$message .= "<td><b>Item</b></td>
					<td><b>Unit Price(LKR)</b></td>
					<td><b>Quantity</b></td>
					<td><b>Total(LKR)</b></td>";
				$message .= "</tr>";
				
				$tot = "";
				
				if(count($cart_arr) > 0)
				{
					foreach ($cart_arr as $cart_entry) :
						$unit_price = $cart_entry['price'];
						$qty = $cart_entry['quantity'];
						$subtotal = $cart_entry['SUBTOTAL'];
		   		
					    $message .= "<div id=\"msgbox\" style=\"display: none;\"></div>";   						
					    $message .=  "<tr>";
						$message .=  "<td>" . $cart_entry['product_title'] . "</td>";
						$message .=  "<td width=\"15%\" align=\"right\">" . number_format($cart_entry['price'], 2, '.', ',') . "</td>";
						$message .=  "<td width=\"12%\" align=\"center\">" . $qty . "</td>";			
						$message .=  "<td width=\"12%\" align=\"right\">";
							$item_price = $unit_price * $qty;
							$price = number_format($item_price, 2, '.', ',');
							$message .= $price;
							$tot = $tot + $item_price;
							$subtotal = number_format($tot, 2, '.', ',');																	
						$message .=  "</td>";
						$message .=  "</tr>";					                        	
					endforeach;
				}
				$message .=  "<tr>";
				$message .=  "<td>&nbsp;</td>";
				$message .=  "<td>&nbsp;</td>";
				$message .=  "<td align=\"center\">Sub Total</td>";
				$message .= "<td align=\"right\"> " . $subtotal . "</td>";
				$message .= "</tr>";
				$message .= "</table>";
                              // echo "Thank you for your order at " . SITENAME." :: Order Ref::".$last_order_id;
			       //	echo $message;
			        $mail = new PHPMailer();
				$mail->IsMail();
				$mail->IsHTML(true);
                                $mail->FromName = 'OfficeSupplies';
                                $mail->From = 'officesupplies.lk';
				$mail->AddAddress($sender_email);
                                $mail->AddCC('info@officesupplies.lk');
                                $mail->AddBCC('induneth87@gmail.com');
                                $mail->AddReplyTo('info@officesupplies.lk');
				$mail->Subject = "Thank you for your order at " . SITENAME." :: Order Ref::".$last_order_id;
				$mail->Body = $message;
				
				if(!$mail->Send())
				{
				   echo "Error sending: " . $mail->ErrorInfo;				   
				}
				else
				{
					$updateProductQty = $modCart->updateProductQty($cart_id);
					//$update_cart = $modCart->updateShoppingCart($cart_id);
                                        $this->sendoutofstockmail();
					
					//if($update_cart)
					//{
						echo "Your order has been placed. One of our member will contact you soon. Thankyou for shopping with " . SITENAME . "<br /><br />";
						echo "<form method='POST' action='" . SITEURL . "index.php/?products/'>
							  <input type='submit' name='btnContinue' id='btnContinue' value='Continue on Shopping' />
							  <input type='hidden' name='savecartid' id='savecartid' value=" . $cart_id . " />
		</form> <br />";
					//}				  
				}
			}			
			include SITETPL . "order/checkout.phtml";
		}
	}

	public function getextranetorder($order_id){

             CommonFunc::loadFile("model/Order.php");
             $modOrder = new FrontOrder();
             $orderlist=$modOrder->getextranetOrderByID($order_id);
             $cart_arr=$modOrder->getCart($orderlist["cart_id"]);
             $carthtml=$this->createcarthtml($cart_arr);
           //  echo $carthtml;
             include SITETPL . "user/extranetorderview.phtml";
	     
        }

        public function cancelorder($order_id){

             CommonFunc::loadFile("model/Order.php");
             $modOrder = new FrontOrder();
             $orderlist=$modOrder->cancelorder($order_id);

        }

          public function createcarthtml($cartval)
        {
                 $grandtotal=0;
		 $carthtml=" <div class='new_cart'>";
		 $carthtml.=" <table width='100%' id='cart_table' border='0' cellspacing='0v cellpadding='0'>";
		 $carthtml.=" <tr>";
		 $carthtml.=" <th width='1%' align='left' class='manuf' scope='col'>Item Code</th>";
		 $carthtml.=" <th align='left' class='desc' scope='col'>product Name</th>";
		 $carthtml.=" <th align='right' class='unit_price' scope='col'>unit price(LKR)</th>";
		 $carthtml.=" <th class='qty' scope='col'>Qty</th>";
                 $carthtml.=" <th align='right' class='total_price' scope='col'>total</th>";
		 $carthtml.=" </tr><tr>";
                 foreach($cartval as $cart){
                  $carthtml.="<tr class='item'>";
	          $carthtml.="<td class='fst'>".$cart['item_code']."</td>";
	          $carthtml.="<td align='center'>".$cart['product_title']."</td>";
		  $carthtml.="<td  align='center'width='16%'>".number_format($cart['price'],2)."</td>";
			    	 $carthtml.="<td align='right'>".$cart['quantity']."</td>";
			    	 $carthtml.="<td align='right'>".number_format($cart['quantity']* $cart['price'],2)."</td>";
			    	 $grandtotal+= (int)$cart['quantity']* (int)$cart['price'];
				 }

			    /*	if($deliverycharge>0){
				    $carthtml.=" </tr><tr>";
				 	$carthtml.=" <td>&nbsp;</td>";
				 	$carthtml.=" <td>&nbsp;</td>";
				 	$carthtml.=" <td>&nbsp;</td>";
				 	$carthtml.=" <td><strong>Delivery Charge LKR</strong></td>";
				 	$carthtml.=" <td>".$deliverycharge."</td>";
				 	$grandtotal+= $deliverycharge;
			    	}
*/
				    $carthtml.=" </tr><tr class='total_amount sumval'> ";
				 	$carthtml.=" <td>&nbsp;</td>";
				 	$carthtml.=" <td>&nbsp;</td>";
				 	$carthtml.=" <td  colspan='2' align='right' class='lbl'> TOTAL LKR </td>";
				 	$carthtml.=" <td colspan='2' align='right' class='amount'>".number_format($grandtotal,2)."</td></tr></tbody></table>";
                              $carthtml.=" </div> ";

		           return  	$carthtml;


            }

       function sendoutofstockmail()
        {
          //  CommonFunc::loadFile(ADAPTOR . "Mail.php");
            $message="";
            $message.=" The products with the follwing Item-codes are out of stock. Please take neccessary actions! <br><br> ";

            $sql = "SELECT * FROM tbl_products WHERE  status=1 and  quantity= 0  ";
            $item_arr = DB::fetchAll($sql);
          if($item_arr){
               foreach($item_arr as  $item){
                $message.= "<br>".$item["item_code"]."  -  ".$item["product_title"]."<br>";
               }

            $message.= " <br>Thank You!";
		//echo $message;
                //exit;

			    $mail = new PHPMailer();
				$mail->IsMail();
				$mail->IsHTML(true);
                                $mail->FromName = 'OfficeSupplies';
                                $mail->From = 'officesupplies.lk';
				$mail->AddAddress('info@officesupplies.lk');
                                $mail->AddCC('pubudu.s@officesupplies.lk');
                                $mail->AddBCC('induneth87@gmail.com');
                                $mail->AddReplyTo('info@officesupplies.lk');
				$mail->Subject = "Products with Out of Stock at " . SITENAME;
				$mail->Body = $message;

				if(!$mail->Send())
				{
				   echo "Error sending: " . $mail->ErrorInfo;
				}
             }


        }

}

?>